package com.dc.bobaoge.project.base.core.util;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.own.business.wallet.entity.po.Wallet;
import com.own.business.wallet.mapper.WalletMapper;
import com.own.component.store.core.util.lock.UniqueLockStoreUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * WalletUtil
 *
 * @author chenxueli
 * @date 2024-01-17 13:41:00
 */
@Slf4j
@Component
public class WalletUtil {

    @Resource
    private WalletMapper walletMapper;

    @Resource
    private UniqueLockStoreUtil uniqueLockStoreUtil;

    /**
     * 检查并初始化钱包数据
     *
     * @param userId 用户id
     * @return 钱包数据
     */
    public Wallet checkAndInit(Long userId) {
        return checkAndInit(userId, null);
    }

    /**
     * 初始化钱包数据
     *
     * @param userId   用户id
     * @param password 密码
     * @return 钱包数据
     */
    public Wallet checkAndInit(Long userId, String password) {
        var wrapper = new LambdaUpdateWrapper<Wallet>().eq(Wallet::getFkUserId, userId);
        var wallet = walletMapper.selectOne(wrapper);
        if (wallet != null) {
            return wallet;
        }
        return init(userId, password, 0);
    }

    /**
     * 初始化钱包数据
     *
     * @param userId   用户id
     * @param password 密码
     * @param balance  余额（分）
     * @return 钱包数据
     */
    public Wallet checkAndInit(Long userId, String password, Integer balance) {
        var wrapper = new LambdaUpdateWrapper<Wallet>().eq(Wallet::getFkUserId, userId);
        var wallet = walletMapper.selectOne(wrapper);
        if (wallet != null) {
            return wallet;
        }
        return init(userId, password, balance);
    }

    /**
     * 修改钱包的支付密码
     *
     * @param userId   用户id
     * @param password 密码
     * @return 钱包数据
     */
    public Wallet updatePassword(Long userId, String password) {
        var wrapper = new LambdaUpdateWrapper<Wallet>().eq(Wallet::getFkUserId, userId);
        var wallet = walletMapper.selectOne(wrapper);
        if (wallet == null) {
            return init(userId, password, 0);
        }
        wallet.setPassword(password);
        walletMapper.updateById(wallet);
        return wallet;
    }

    /**
     * 初始化钱包
     *
     * @param userId   用户id
     * @param password 密码
     * @param balance  余额（分）
     * @return 钱包数据
     */
    private Wallet init(Long userId, String password, Integer balance) {
        return uniqueLockStoreUtil.operation("o:c:wallet:" + userId, () -> {
            var po = new Wallet();
            po.setFkUserId(userId);
            po.setBalance(balance);
            po.setFreezeAmount(0);
            po.setPassword(password);
            po.setIsWithoutPassword(0);
            walletMapper.insert(po);
            return po;
        }, Wallet.class);
    }

}
